<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择物料" prop="itemId">
        <el-select filterable v-model="queryParams.itemId" placeholder="请选择物料" class="full-width">
          <el-option
            v-for="item in allItemList"
            :key="item.id"
            :label="item.itemName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号" prop="itemNo">
        <el-input
          v-model="queryParams.itemNo"
          placeholder="请输入物料编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库房" prop="storageRoom">
        <el-select v-model="queryParams.storageRoom" placeholder="请选择库房" clearable size="small">
          <el-option
            v-for="dict in dict.type.item_storage_room"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库区" prop="storageArea">
        <el-select v-model="queryParams.storageArea" placeholder="请选择库区" clearable size="small">
          <el-option
            v-for="dict in dict.type.item_storage_area"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库位" prop="storagePosition">
        <el-select v-model="queryParams.storagePosition" placeholder="请选择库位" clearable size="small">
          <el-option
            v-for="dict in dict.type.item_storage_position"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bussiness:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="物料编号" align="center" prop="itemNo" />
      <el-table-column label="物料数量" align="center" prop="itemNum" />
      <el-table-column label="库房" align="center" prop="storageRoom">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.item_storage_room" :value="scope.row.storageRoom"/>
        </template>
      </el-table-column>
      <el-table-column label="库区" align="center" prop="storageArea">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.item_storage_area" :value="scope.row.storageArea"/>
        </template>
      </el-table-column>
      <el-table-column label="库位" align="center" prop="storagePosition">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.item_storage_position" :value="scope.row.storagePosition"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="inventoryStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inventory_status" :value="scope.row.inventoryStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.inventoryStatus == 'normal'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRent(scope.row)"
            v-hasPermi="['bussiness:rent:add']"
          >租赁</el-button>
          <el-button
            v-if="scope.row.inventoryStatus == 'normal'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDelivery(scope.row)"
            v-hasPermi="['bussiness:delivery:add']"
          >出库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改出库信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库类型" prop="deliveryType">
          <el-select v-model="form.deliveryType" placeholder="请选择出库类型" class="full-width">
            <el-option
              v-for="dict in dict.type.item_delivery_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出库数量" prop="deliveryNum">
          <el-input v-model.number="form.deliveryNum" placeholder="请输入出库数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加租赁　对话框 -->
    <el-dialog :title="rent.title" :visible.sync="rent.open" width="500px" append-to-body>
      <el-form ref="rentForm" :model="rent.form" :rules="rentRules" label-width="80px">
        <el-form-item label="当前雪具">
          <template>
            <span>{{ rent.form.itemName }}</span>
          </template>
        </el-form-item>
        <el-form-item label="租赁数量">
          <template>
            <span>{{ rent.form.itemNum }}</span>
          </template>
        </el-form-item>
        <el-form-item label="当前日期">
          <template>
            <span>{{ parseTime(rent.form.currentDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-form-item>
        <el-form-item label="租赁时间" prop="time">
          <el-time-select
            placeholder="租赁起始时间"
            v-model="rent.form.startTime"
            :picker-options="{
              start: pickerStartTime,
              step: '00:15',
              end: pickerEndTime
            }">
          </el-time-select> ~ 
          <el-time-select
            placeholder="租赁结束时间"
            v-model="rent.form.endTime"
            :picker-options="{
              start: purchaseEndTime,
              step: '00:15',
              end: pickerEndTime
            }">
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRentForm">确 定</el-button>
        <el-button @click="cancelRent">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, getInventory, delInventory, addInventory, updateInventory } from "@/api/bussiness/inventory";
import { listItem } from "@/api/bussiness/item";
import { addDelivery } from "@/api/bussiness/delivery";
import { addRent } from "@/api/bussiness/rent";

export default {
  name: "Inventory",
  dicts: ['item_storage_room', 'item_storage_area', 'item_storage_position', 'inventory_status', 'item_delivery_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存信息表格数据
      inventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemId: null,
        itemNo: null,
        storageRoom: null,
        storageArea: null,
        storagePosition: null,
        inventoryStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deliveryType: [
          {required: true, message: '请选择出库类型', blur: 'change'}
        ],
        deliveryNum: [
          {required: true, type: 'number', message: '请填写出库数量', blur: 'change'}
        ]
      },
      // 所有物料集合
      allItemList: [],
      // 当前点击的出库库存记录
      inventoryInfo: null,
      /** 租赁弹窗相关参数 */
      rent: {
        open: false,
        title: '请选择租赁时间',
        form: {
          itemName: '',
          itemNum: '',
          currentDate: '',
          startTime: '',
          endTime: ''
        }
      },
      rentRules: {

      },
      // 预约时间 开始时间
      pickerStartTime: '08:00',
      // 预约时间 截至时间
      pickerEndTime: '21:00',
      // 可选日期空间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24*60*60*1000;
        }
      },
      // 定时任务
      timer: '',
      // 点击租赁的当前行
      currentRentRow: {}
    };
  },
  created() {
    this.getList();
    // 获取所有物料列表
    this.getAllItemList();
  },
  mounted(){
    this.timer = setInterval(()=> {this.getPickerStartTime()}, 30000)
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  computed: {
    purchaseEndTime: function (){
      this.rent.form.endTime = ''
      if(this.rent.form.startTime){
        let time = this.rent.form.startTime.split(':')
        let tmp_hour = time[0] / 1 + 1
        let tmp_min = time[1] / 1
        // 判断是否超过结束时间
        let endT = this.pickerEndTime.split(':')
        if(tmp_hour >= endT[0]){
          tmp_hour = endT[0]
          tmp_min = endT[1]
        }
        return (tmp_hour < 10 ? '0' + tmp_hour : tmp_hour) + ':' + (tmp_min == 0? '00' : tmp_min)
      }
    }
  },
  methods: {
    // 获取可选开始时间
    getPickerStartTime(){
      // 如果预约日期是今天，做处理。
      let dt = this.rent.form.currentDate
      if(dt){
        let ndt = new Date()
         if(dt.getFullYear() == ndt.getFullYear() && dt.getMonth() == ndt.getMonth() && dt.getDate() == ndt.getDate()){
            let hh = new Date().getHours()
            let mm = new Date().getMinutes()
            let tmp_hh, tmp_mm
            tmp_hh = hh
            // 如果分钟大于45，小时+1
            if(mm < 15){
              tmp_mm = '15'
            }else if( 15 < mm && mm < 30){
              tmp_mm = '30'
            }else if( 30 < mm && mm < 45){
              tmp_mm = '45'
            }else if( mm >= 45){
              tmp_mm = '00'
              tmp_hh = hh + 1
            }
            console.log(tmp_hh + ":" + tmp_mm)
            if(tmp_hh < 8){
              return this.pickerStartTime = '08:00'
            }
            return this.pickerStartTime = tmp_hh + ":" + tmp_mm
         }
      }
      return this.pickerStartTime = '08:00'
    },
    /** 查询所有物料列表 **/
    getAllItemList(){
      listItem().then(response => {
        this.allItemList = response.rows;
      });
    },
    /** 查询库存信息列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: null,
        itemId: null,
        itemNo: null,
        itemNum: null,
        storageRoom: null,
        storageArea: null,
        storagePosition: null,
        inventoryStatus: null
      };
      this.resetForm("form");
      this.inventoryInfo = null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 出库按钮操作 */
    handleDelivery(row) {
      if(row.inventoryStatus != 'normal' && row.itemNum < 1){
        return this.$modal.msgError("当前物料库存为0，无法出库！")
      }
      this.reset();
      this.inventoryInfo = row
      this.open = true;
      this.title = "添加出库信息";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let { deliveryType, deliveryNum, remark } = this.form
          let { inventoryId, itemId, itemNo, storageRoom, storageArea, storagePosition, itemNum } = this.inventoryInfo
          if(deliveryNum > itemNum){
            return this.$modal.msgError("当前物料库存数量为：" + itemNum +"，出库数量必须小于等于库存数量！");
          }
          let params = {
            inventoryId,
            itemId,
            itemNo,
            storageRoom,
            storageArea,
            storagePosition,
            deliveryType,
            deliveryNum,
            remark
          }
          addDelivery(params).then(response => {
            this.$modal.msgSuccess("出库成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryIds = row.inventoryId || this.ids;
      this.$modal.confirm('是否确认删除库存信息编号为"' + inventoryIds + '"的数据项？').then(function() {
        return delInventory(inventoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bussiness/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    },
    /** 租赁按钮 */
    handleRent(row){
      // 判断雪具状态
      if(row.inventoryStatus != 'normal'){
        return this.$modal.msgError("当前雪具已被租赁，请更换其他雪具！");
      }
      // 制空对象
      this.$set(this.rent, 'form', {
        currentDate: '',
        startTime: '',
        endTime: ''
      })
      this.rent.form.currentDate = new Date()
      this.rent.form.itemName = row.itemName
      this.rent.form.itemNum = row.itemNum
      this.currentRentRow = row
      this.getPickerStartTime()
      // 打开弹窗
      this.rent.open = true
      console.log(row)
    },
    /** 处理租赁确认按钮 */
    submitRentForm(){
      // 1. 判空
      let tmp_currentDate = this.rent.form.currentDate
      if(!tmp_currentDate){
        return this.$modal.msgError("当前日期获取失败！请刷新页面！");
      }
      let {startTime, endTime} = this.rent.form
      if(!startTime){
        return this.$modal.msgError("请选择租赁开始时间！");
      }
      if(!endTime){
        return this.$modal.msgError("请选择租赁结束时间！");
      }
      tmp_currentDate = this.parseTime(tmp_currentDate, '{y}-{m}-{d}')
      let tmp_startTime = new Date(tmp_currentDate + ' ' + startTime + ':00');
      let tmp_endTime = new Date(tmp_currentDate + ' ' + endTime+ ':00');
      console.log('1', tmp_endTime.getTime() - tmp_startTime.getTime())
      if(tmp_endTime.getTime() - tmp_startTime.getTime() < 3600000){
        return this.$modal.msgError("租赁时间最少为1个小时，请重新选择租赁起止时间！");
      }

      // 2.调用接口
      let date = this.rent.form.currentDate
      let comDate = date.getFullYear() + '-' 
          + ((date.getMonth() + 1) < 10 ? '0'+ (date.getMonth() + 1) : date.getMonth() + 1) + '-' 
          + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      let rentStartTime = comDate + ' ' + startTime + ':00'
      let rentEndTime = comDate + ' ' + endTime + ':00'
      console.log(rentStartTime, rentEndTime)
      let {inventoryId, itemNum} = this.currentRentRow
      let params = {
        rentStartTime,
        rentEndTime,
        inventoryId,
        rentQuantity: itemNum
      }
      addRent(params).then(res=>{
        this.$modal.msgSuccess("租赁成功！");
        this.rent.open = false;
        this.getList();
      })
    },
    /** 处理租赁取消按钮 */
    cancelRent(){
      this.rent.open = false
    }
  }
};
</script>
